24/09/2008

How to bind a DropdownList with VB.Net

Posted in How to..., VB.Net 2.0 tagged , , , , a 05:14 por nestedsolutions

Previous knowledge: How Create database, tables, key values and basically drag and drop controls with VS2005, VS2008 or even the Web Developer Express 2005 & 2008.

Today, we´re gonna demostrate how to use the dropdown control from the ASP.Net toolbar, in fact; it’s very easy. So, the first thing we need to know is that we can bind to almost ANY source or collection of items, I mean the datatables, arrays, hashtables. But for now, let us focus on a datatable filled dropdownlist from a database.

The structure for the source table is:

 The id_client field has its property Identity set to true and it’s the key column as well. So it cans auto generate the field value, this way there is no need to care for assigning the value. We got this table with the following data:

Next step, it’s to place the controls in our page. Write the following html code (or drag & drop the control from the toolbar) inside the body tag:

  <asp:DropDownList ID=»DropDownList1« runat=»server«>

    </asp:DropDownList> 

You can rename the control ID tag to: “ddlCliente” just for put a naming standard. In the code behind page load place this code:

—————————————–

‘EXIT THE FUNCTION IF WE ARE DEALING
‘WITH A PAGE ‘RELOAD’

If IsPostBack Then
        Exit Sub
End If

SET THE CONNECTION STRING
Dim sCNX As String = «Data Source=dohko1;Initial Catalog=Pruebas;Persist Security Info=True;User ID=sa;Password=sa»

SET THE CONNECTION
Dim sqlConnection As New System.Data.SqlClient.SqlConnection
sqlConnection.ConnectionString = sCNX

‘SET THE COMMAND QUERY TO OBTAIN THE DATA FROM THE DATABASE
Dim sqlCommand As New System.Data.SqlClient.SqlCommand
‘SET THE QUERY
sqlCommand.CommandText = «SELECT ID_CLIENT, FULL_NAME FROM CLIENTS»

‘SET THE CONNECTION TO THE COMMAND
sqlCommand.Connection = sqlConnection

‘SET THE OBJECT WHERE THE DATA WILL BE STORED IN MEMORY
Dim dsCLIENTS As New System.Data.DataSet

‘SET THE DATA ADAPTER THAT MAKES SOME KIND OF DATA LAYER
Dim sqlAdapter As New System.Data.SqlClient.SqlDataAdapter

‘OPEN THE CONNECTION
sqlConnection.Open()

‘ESTABLISH THE COMMAND TO EXECUTE
sqlAdapter.SelectCommand = sqlCommand

‘FILL THE DATASET WITH ALL THE PREVIOUS OBJECTS IN THE DATASET
sqlAdapter.Fill(dsCLIENTS)

‘CLOSE THE CONNECTION, ONCE WE HAD GET THE DATA WE DONT NEED IT OPEN ANY LONGER
sqlConnection.Close()

‘SET THE PROPERTY FROM WHERE TO GET THE DATA TO SHOW
‘THIS IS THE VISIBLE PART
DropDownList1.DataTextField = «FULL_NAME»

‘SET THE KEY PROPERTY
DropDownList1.DataValueField = «ID_CLIENT»

‘SET THE DATASOURCE
DropDownList1.DataSource = dsCLIENTS.Tables(0).DefaultView

‘BIND THE CONTROL WITH THE DATA
DropDownList1.DataBind()

—————————————–

Press F5 to run your website, wait just a bit… and “magic!” you got the control bounded to data from database. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

It’s important to advice the next table:

 

Property

Description

DropDownList1.SelectedIndex

Gets the index of the selected item. Returns -1 where there’s no item selected.

DropDownList1.SelectedValue

Gets the value (the dataValue property previously assigned in the data bind) of the selected item.

DropDownList1.SelectedItem

Get the item (both text and value) selected.

I think this is all the basics you need to know about the dropdownlist control.

Please note the Autopostback property and see the changes in the code.

If you want to execute some operations after you have changed the selection in the dropdown, set the property Autopostback set to true and double click the control to obtain the event handler for the “SelectedIndexChanged”. Now you can write here the code for this event:

—————————————————

 

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged

        ‘SOME OPERATIONS AFTER THE SELECTED INDEX HAS CHANGED

    End Sub

—————————————————

 

This same “How to…” can easily apply to a listbox control. Please feel free to try.

 I hope somebody finds this little quick manual reference useful.

 So be it.

 Over.

2 comentarios »

  1. sandy said,

    Hola Marcos…
    Me estoy iniciando en .NET y tu post me ha ayudado a entender mucho mejor el funcionamiento del DDL, gracias, hacia falta algo asi de detallado, seguire visitando tu post, Gracias…
    Si tengo alguna duda te la hare saber.

    Saludos…

  2. Eniko Smith said,

    You have very properly explained how to bind a DropdownList with VB.Net with good examples with images. You have made this work very easy with your proper description.

    Good work…. done by you…..

    thanks….


Deja un comentario